﻿using System;

namespace WooEngine.Utility.Security.Base
{
	[System.Serializable]
	public class EncryptDouble
	{
		public static System.Random random = new System.Random();

		private int SECRET_KEY;

		private byte[] _value;

		private byte[] _convertTempBytes;
		public double Value
		{
			set
			{
				byte[] bits = BitConverter.GetBytes(value);
				for(int i=0 ; i < bits.Length ; i++)
				{
					bits[i] = (byte)(bits[i] ^ SECRET_KEY);
				}
				_value = bits;
			}
			get 
			{
				if(_convertTempBytes == null || _convertTempBytes.Length != _value.Length) 
				{
					_convertTempBytes = new byte[_value.Length];
				}

				for(int i=0 ; i < _value.Length ; i++)
				{
					_convertTempBytes[i] = (byte)(_value[i] ^ SECRET_KEY);
				}
				return BitConverter.ToDouble(_convertTempBytes, 0);
			}
		}

		public EncryptDouble()
		{
			SECRET_KEY = Convert.ToByte(random.Next(0, 255));
		}

		public static EncryptDouble Get(double v)
		{
			EncryptDouble ed = v;
			return ed;
		}

		public static implicit operator EncryptDouble(double value)
		{
			EncryptDouble encryptDouble = new EncryptDouble();
			encryptDouble.Value = value;

			return encryptDouble;
		}

		public static implicit operator Double(EncryptDouble encryptDouble)
		{
			if (encryptDouble == null) { return 0D; }
			return encryptDouble.Value;
		}

		public string ToString(string format)
		{
			return Value.ToString(format);
		}

		public override string ToString()
		{
			return Value.ToString();
		}
	}
}